package com.logistics.redislock;

import com.alibaba.fastjson.JSON;
import com.logistics.compont.ResponseApi;
import com.logistics.pojo.Orderinfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
@RestController
public class RedisLockTest {

    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    @Autowired
    public RedisLock redisLock;

    @Test
    public void insertRedis(){

        Orderinfo orderInfo1 = new Orderinfo();
        orderInfo1.setOnum("1");
        orderInfo1.setEid(1);

        Orderinfo orderInfo2 = new Orderinfo();
        orderInfo2.setOnum("2");
        orderInfo2.setEid(2);

        Orderinfo orderInfo3 = new Orderinfo();
        orderInfo3.setOnum("3");
        orderInfo3.setEid(3);

        List<Orderinfo> orderinfoList = new ArrayList<Orderinfo>();
        orderinfoList.add(orderInfo1);
        orderinfoList.add(orderInfo2);
        orderinfoList.add(orderInfo3);

        orderinfoList.forEach(x -> {
            stringRedisTemplate.boundHashOps("order").put(x.getOnum(), JSON.toJSONString(x));
        });

        System.out.println("入库成功。");
    }

    @GetMapping("/getOrder")
    public void getOrder(String onum){

        //定义redis锁的key
        String lockkey = "orderkey";

        //定义锁的超时时间 1s
        Long ex = 1000L;
        String valueTimeout = System.currentTimeMillis()+ex+"";

        //判断锁是否加成功
        boolean lock = redisLock.lock(lockkey, valueTimeout);

        if(lock){
            String orderJson = (String)stringRedisTemplate.boundHashOps("order").get(onum);
            Orderinfo order = JSON.parseObject(orderJson, Orderinfo.class);
            System.out.println("订单："+order.getOnum() +" 被抢到。");
            stringRedisTemplate.boundHashOps("order").delete(onum);

            //释放锁
            redisLock.unlock(lockkey,valueTimeout);
        }

    }

}
